//
//  RootViewController.m
//  QuanNengSaoMiaoZhuShou
//
//  Created by lanou3g on 16/3/10.
//  Copyright © 2016年 于博文. All rights reserved.
//

#import "RootViewController.h"


#import "PictureCollectionViewCell.h"
#import "PictureTableViewCell.h"

#define kGap kSCreamWidth_100*14
@interface RootViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate>

@property (strong,nonatomic) UICollectionView *PicCollectionView;
@property (strong,nonatomic) UITableView *PicTableView;
@property (assign,nonatomic,getter = isLongEditing) BOOL longPressEdit;
@property (assign,nonatomic,getter = isTapEditing) BOOL tapPressEdit;
@property (assign,nonatomic,getter=isList) BOOL ViewOrList;
@property (strong,nonatomic) UIButton *cameraBtn;
@property (strong,nonatomic) UIButton *listBtn_b;
@property (strong,nonatomic) UIBarButtonItem *ButtonItem;
@property (strong,nonatomic) NSMutableArray *indexArray;

@end

//注册cell
static NSString *const cellReuseID = @"PictureTableViewCell";
static NSString *const cellHeaderReuseID = @"cellheaderReuseIdentifier";
static NSString *const ItemReuseID = @"systemCellReuseIdentifier";
//增补视图重用标识符
static NSString *const headerReuseID = @"headerReuseIdentifier";

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    [self setTableView];
    //集合视图
    [self setCollectionView];
    //右按钮
    [self setBtn];
    //右按钮
    [self setRightAction];
  
}

#pragma mark -----------tableView-----------
- (void) setTableView {
    self.PicTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCreamWidth, kSCreamHeight) style:(UITableViewStylePlain)];
    self.PicTableView.delegate = self;
    self.PicTableView.dataSource = self;
    [self.view addSubview:self.PicTableView];
    [self.PicTableView registerNib:[UINib nibWithNibName:@"PictureTableViewCell" bundle:nil] forCellReuseIdentifier:cellReuseID];
    [self.PicTableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:cellHeaderReuseID];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, -200, kSCreamWidth, 200)];
    view.alpha = 0.9;
    view.backgroundColor = kTintColor_green;
    
    self.PicTableView.showsVerticalScrollIndicator = false;
    [self.PicTableView addSubview:view];
    [self.view addSubview:_PicTableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.imgarray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 12*kSCreamWidth_100;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    [self setControllerView];
    UIView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellHeaderReuseID];
    [header addSubview: self.controllerView];
    return  header;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseID forIndexPath:indexPath];
    //如果没有手势
    UILongPressGestureRecognizer *LongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
    LongPress.minimumPressDuration = 0.7;
    NSLog(@"%d",_longPressEdit);
    if (!_longPressEdit) {
        cell.check_of.alpha = 0;
        cell.check_on.alpha = 0;
    }else {
        cell.check_of.alpha = 1;
    }
    
    [LongPress setEnabled:YES];
    LongPress.delegate = self;
    cell.contentView.tag = indexPath.row + 10000;
    [cell.contentView addGestureRecognizer:LongPress];
    //添加轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [tap setEnabled:NO];
    if (!_tapPressEdit) {
        cell.check_on.alpha = 0;
        [tap setEnabled:YES];
    }
     tap.delegate = self;
    Picture_model *model = [[Picture_model alloc]init];
    model = self.imgarray[indexPath.row];
    cell.imgView.image = model.imag;
    cell.date.text = model.dateTime;
    cell.Name.text = model.name;
    [cell.contentView addGestureRecognizer:tap];
    model = nil;
    return cell;
    //集合视图
//    [self setCollectionView];
    //[self setCollectionView];
   
}


#pragma mark -----------集合视图-------------
//注册集合视图
-(void)setCollectionView {
    UICollectionViewFlowLayout *flowlayou = [[UICollectionViewFlowLayout alloc]init];
    flowlayou.minimumLineSpacing = 10;//最小间隙,
    flowlayou.minimumInteritemSpacing = 10;
    flowlayou.headerReferenceSize = CGSizeMake(kSCreamWidth, 12*kSCreamWidth_100);
    //到边距离
    flowlayou.sectionInset = UIEdgeInsetsMake(5, 13, 10, 13);
     self.PicCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, kSCreamWidth, kSCreamHeight) collectionViewLayout:flowlayou];
    [self.PicCollectionView registerNib:[UINib nibWithNibName:@"PictureCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellReuseID];
    //注册增补视图
    [self.PicCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseID];
    
    self.PicCollectionView.delegate = self;
    self.PicCollectionView.dataSource = self;
    self.PicCollectionView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50*kSCreamWidth_100-50 , -50, 100, 50)];
    label.text = @"正在同步.....";
    label.textAlignment =  NSTextAlignmentCenter ;
    label.textColor = [UIColor grayColor];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, -200, kSCreamWidth, 200)];
    view.alpha = 0.9;
    view.backgroundColor = kTintColor_green;
    
    self.PicCollectionView.showsVerticalScrollIndicator = false;
    [self.PicCollectionView addSubview:view];
    [self.PicCollectionView addSubview:label];
    [self.view addSubview:_PicCollectionView];
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return  CGSizeMake(kSCreamWidth_100 *28,kSCreamWidth_100 *45);
}
//设置透视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    [self setControllerView];
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseID forIndexPath:indexPath];
    [header addSubview: self.controllerView];
    return  header;
}


//每一个分区有多少个Item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.imgarray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PictureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellReuseID forIndexPath:indexPath];
    //如果没有手势
     UILongPressGestureRecognizer *LongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
    LongPress.minimumPressDuration = 0.7;
    NSLog(@"%d",_longPressEdit);
    if (!_longPressEdit) {
        cell.check_of.alpha = 0;
        cell.check_on.alpha = 0;
    }else {
    cell.check_of.alpha = 1;
    }
   
    [LongPress setEnabled:YES];
    LongPress.delegate = self;
    cell.contentView.tag = indexPath.row + 10000;
    [cell.contentView addGestureRecognizer:LongPress];
    //添加轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
     [tap setEnabled:NO];
    if (!_tapPressEdit) {
         cell.check_on.alpha = 0;
        [tap setEnabled:YES];
    }
    tap.delegate = self;
    Picture_model *model = [Picture_model new];
    model = self.imgarray[indexPath.row];
    cell.imgView.image = model.imag;
    cell.date.text = model.dateTime;
    cell.Name.text = model.name;
    [cell.contentView addGestureRecognizer:tap];
   
    return cell;
}
#pragma mark ------手势---------------
//item的轻拍按钮
-(void)tapAction:(UITapGestureRecognizer *)sender{
    if (!_ViewOrList){
        PictureCollectionViewCell *cell = [self.PicCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:sender.view.tag -10000 inSection:0]];
        if (_tapPressEdit && _longPressEdit && cell.check_on.alpha == 0) {
            int i = 0;
            NSNumber *a = [NSNumber numberWithInt:(int)sender.view.tag - 10000];
            for (NSNumber *dd in _indexArray) {
                if (dd == a) {
                    i++;
                }
            }
            if (i == 0) {
                [self.indexArray addObject:a];
                cell.check_on.alpha = 1;
            }
            
        }else {
            NSNumber *a = [NSNumber numberWithInt:(int)sender.view.tag - 10000];
            if (self.indexArray != 0) {
                int i;
                for (NSNumber *dd in _indexArray) {
                    if (dd == a) {
                        i++;
                    }
                }
                if (i > 0) {
                    [self.indexArray removeObject:a];
                    cell.check_on.alpha = 0;

                }
            }
                    }
    }else {
       PictureTableViewCell *cell = [self.PicTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:sender.view.tag -10000 inSection:0]];
        if (_tapPressEdit && _longPressEdit && cell.check_on.alpha == 0) {
            int i = 0;
            NSNumber *a = [NSNumber numberWithInt:(int)sender.view.tag - 10000];
            for (NSNumber *dd in _indexArray) {
                if (dd == a) {
                    i++;
                }
            }
            if (i == 0) {
                [self.indexArray addObject:a];
                cell.check_on.alpha = 1;
            }
            
        }else {
            NSNumber *a = [NSNumber numberWithInt:(int)sender.view.tag - 10000];
            if (self.indexArray != 0) {
                int i;
                for (NSNumber *dd in _indexArray) {
                    if (dd == a) {
                        i++;
                    }
                }
                if (i > 0) {
                    [self.indexArray removeObject:a];
                }
            }
            cell.check_on.alpha = 0;
        }
     }
  }
//item的长按按钮
- (void)longPressAction:(UILongPressGestureRecognizer *)sender {
    //解决响应两次的问题
    if (sender.state == UIGestureRecognizerStateEnded) {
        return;
    } else if (sender.state == UIGestureRecognizerStateBegan) {
        [self setEditingState];
        [self setBtn_title];
        [self setRightButtonItem];
        [self reloadViewCellOrItem];
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    
}


#pragma mark--------------按钮视图设置-------------------
 //设置根视图控制器_导航栏右键
-(void)setRightAction{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UINavigationController *na = (UINavigationController *)app.draw.rootVC;
    UIViewController *vc = na.viewControllers[0];
    vc.navigationItem.rightBarButtonItem = ({
         _ButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightAction:)];
        _ButtonItem;
    });

}
//右键按钮
- (void)rightAction:(UIBarButtonItem *)sender {
     [self setEditingState];
     [self setRightButtonItem];
     [self setBtn_title];
     [self reloadViewCellOrItem];
}

#pragma mark------------导航栏四个按钮--------------
//设置导航栏下的四个按钮_备用
-(void)setControllerView {
     NSString *nameString;
    if (!_ViewOrList) {
        nameString = @"list_home_sort－";
    }else {
    nameString = @"icon_home_thumbview";
    }
    self.controllerView = [[UIView alloc]initWithFrame:CGRectMake(0,0*kSCreamWidth_100, kSCreamWidth, 12*kSCreamWidth_100)];
    self.controllerView.backgroundColor = [UIColor redColor];
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
   listBtn.frame = CGRectMake(5*kSCreamWidth_100, 0*kSCreamWidth_100, 12*kSCreamWidth_100, 12*kSCreamWidth_100);
  
    [listBtn setImage:[UIImage imageNamed:@"search_api_mtrl_alpha"] forState:(UIControlStateNormal)];
    [listBtn setImage:[UIImage imageNamed:@"hight_small"] forState:(UIControlStateHighlighted)];
    [self.controllerView addSubview:listBtn];
    _listBtn_b = [UIButton buttonWithType:UIButtonTypeCustom];
    _listBtn_b.frame = CGRectMake(CGRectGetMaxX(listBtn.frame)+kGap, 0*kSCreamWidth_100, 12*kSCreamWidth_100, 12*kSCreamWidth_100);
    [_listBtn_b setImage:[UIImage imageNamed:nameString] forState:(UIControlStateNormal)];
    [_listBtn_b addTarget:self action:@selector(ListOrItem:) forControlEvents:(UIControlEventTouchUpInside)];
     [_listBtn_b setImage:[UIImage imageNamed:@"hight_small"] forState:(UIControlStateHighlighted)];
    [self.controllerView addSubview:_listBtn_b];

    UIButton *listBtn_c = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn_c.frame = CGRectMake(CGRectGetMaxX(_listBtn_b.frame)+kGap, 0*kSCreamWidth_100, 12*kSCreamWidth_100, 12*kSCreamWidth_100);

    [listBtn_c setImage:[UIImage imageNamed:@"search_api_mtrl_alpha"] forState:(UIControlStateNormal)];
    [listBtn_c setImage:[UIImage imageNamed:@"hight_small"] forState:(UIControlStateHighlighted)];
    [self.controllerView addSubview:listBtn_c];
    
    UIButton *listBtn_d = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn_d.frame = CGRectMake(CGRectGetMaxX(listBtn_c.frame)+ kGap, 0*kSCreamWidth_100, 12*kSCreamWidth_100, 12*kSCreamWidth_100);
    [listBtn_d addTarget:self action:@selector(listBtn_dAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [listBtn_d setImage:[UIImage imageNamed:@"picture_to_gallery"] forState:(UIControlStateNormal)];
    [listBtn_d setImage:[UIImage imageNamed:@"hight_small"] forState:(UIControlStateHighlighted)];
    self.controllerView.backgroundColor = kTintColor_green;
    [self.controllerView addSubview:listBtn_d];
 }
#pragma mark -------切换列表视图--------------
- (void)ListOrItem:(UIButton *)sender {
    if (_longPressEdit) {
        [self showAlertView:@"正在编辑,请稍后"];
        return;
    }
    if (!_ViewOrList) {
        [self.PicCollectionView removeFromSuperview];
        [self setTableView];
        _ViewOrList = YES;
    }else {
        [self.PicTableView removeFromSuperview];
        [self setCollectionView];
        _ViewOrList = NO;
    
    }
    [self reloadViewCellOrItem];
    [self.cameraBtn removeFromSuperview];
    [self setBtn];
}
#pragma mark-------------本地相册------------
//调用本地相册
-(void)listBtn_dAction:(UIButton *)sender {
    
    if (!_longPressEdit) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        //设置选择后的图片可被编辑
        picker.allowsEditing = YES;
        [self presentModalViewController:picker animated:YES];
    }else {
        [self showAlertView:@"编辑状态,继续操作,请先退出"];
      }
 }

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
         //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
          //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
       NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath, @"/image.png"];
#pragma clang diagnostic push
#pragma clang diagnostic ignored"ALAssetsLibraryAssetForURLResultBlock"
    // 被夹在这中间的代码针对于此警告都会无视并且不显示出来
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
        {
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            NSString *fileName = [representation filename];
            Picture_model *model = [Picture_model new];
            model.dateTime = [super getCurrentTime];
            model.name = fileName;
            model.imag = image;
            [self.imgarray addObject:model];
            dispatch_async(dispatch_get_main_queue(), ^{
                //关闭相册界面
            [picker dismissModalViewControllerAnimated:YES];
                [self reloadViewCellOrItem];
                
            });
          
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageURL
                       resultBlock:resultblock
                      failureBlock:nil] ;
 #pragma clang diagnostic pop
     }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissModalViewControllerAnimated:YES];
}
//设置照相机调用按钮
-(void)setBtn{
    _cameraBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _cameraBtn.frame = CGRectMake(CGRectGetMaxX(self.view.frame)-25*kSCreamWidth_100, CGRectGetMaxY(self.view.frame)-40*kSCreamWidth_100, 20*kSCreamWidth_100, 20*kSCreamWidth_100);
    [self setBtn_title];
    [_cameraBtn addTarget:self action:@selector(cameraAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_cameraBtn];
    [self.view bringSubviewToFront:_cameraBtn];
 }

//跳转相机界面
-(void)cameraAction {
     if (!_longPressEdit) {
        CameraViewController *cameraVC = [[CameraViewController alloc]initWithNibName:@"CameraViewController" bundle:nil];
         //[self.navigationController presentViewController:cameraVC animated:YES completion:nil];
         UINavigationController *naV = [[UINavigationController alloc]initWithRootViewController:cameraVC];
        [self presentViewController:naV animated:YES completion:nil];
    }else {
    //删除数组
        if (self.indexArray != nil && self.imgarray != nil) {
            for (NSNumber *a in _indexArray) {
            [self.imgarray removeObjectAtIndex:[a intValue]];
            
            }
            [self.indexArray removeAllObjects];
            [self setAlpha];
            if (self.imgarray.count == 0) {
                _longPressEdit = NO;
                _tapPressEdit = NO;
                _PicCollectionView.bounces = YES;
                [self setBtn_title];
                [self setRightButtonItem];
            }
            
            [self reloadViewCellOrItem];
        }else {
        
        //可以加提示
        }
     }
}
#pragma mark -----------懒加载------------
-(NSMutableArray *)imgarray {
    if (!_imgarray) {
        _imgarray = [NSMutableArray arrayWithCapacity:5];
    }
    return _imgarray;

}
- (NSMutableArray *)indexArray {
    if (!_indexArray) {
        _indexArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _indexArray;
}


#pragma mark ---------------提示框--------------------
//提示框
- (void)showAlertView:(NSString *)message {
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ---------------设置编辑状态及button背景---------
//不同编辑状态的bool值
-(void)setEditingState {
    
    if (self.imgarray.count == 0) {
        return;
    }
    if (!_longPressEdit) {
        _longPressEdit = YES;
        _tapPressEdit = YES;
        _PicCollectionView.bounces = NO;
        _PicTableView.bounces = NO;
    }else {
        _longPressEdit = NO;
        _tapPressEdit = NO;
        _PicCollectionView.bounces = YES;
        _PicTableView.bounces = YES;
    }
}
//相册button的背景图
-(void)setBtn_title {
 
    if (!_longPressEdit) {
        [_cameraBtn setImage:[UIImage imageNamed:@"ic_capture_capure"] forState:(UIControlStateNormal)];
         [_cameraBtn setImage:[UIImage imageNamed:@"hight_button"] forState:(UIControlStateHighlighted)];
    }else{
        [_cameraBtn setImage:[UIImage imageNamed:@"deledge"] forState:(UIControlStateNormal)];
    }
}
-(void)setRightButtonItem {
    if (!_longPressEdit) {
        [_ButtonItem setTitle:@"编辑"];
    }else{
        [_ButtonItem setTitle:@"取消"];
    }
}
- (void)setAlpha {
    if (!_ViewOrList) {
        NSArray *arr = [self.PicCollectionView visibleCells];
        for (PictureCollectionViewCell *cell in arr) {
            cell.check_on.alpha = 0;
        }
    }else {
        NSArray *arr = [self.PicTableView visibleCells];
        for (PictureTableViewCell *cell in arr) {
            cell.check_on.alpha = 0;
        }
    }

}

#pragma mark -----刷新UI --------------
- (void) reloadViewCellOrItem {
    if (!_ViewOrList) {
        [self.PicCollectionView reloadData];
    }else {
        [self.PicTableView reloadData];
    }
}

@end
